<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkContact\Listener;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Corp\Event\CreateCorpEvent;
use MoChat\App\WorkContact\Contract\ContactFieldContract;
use Psr\Container\ContainerInterface;

/**
 * 创建企业事件.
 *
 * @Listener(priority=9999)
 */
class CreateCorpListener implements ListenerInterface
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @var ContactFieldContract
     */
    private $contactFieldService;

    public function listen(): array
    {
        return [
            CreateCorpEvent::class,
        ];
    }

    public function process(object $event)
    {
        try {
            $message = $event->message;
            $this->logger = $this->container->get(StdoutLoggerInterface::class);
            $this->contactFieldService = $this->container->get(ContactFieldContract::class);
            $corpId = $message['corpId'];

            $initContactFields = $this->contactFieldService->getInitContactFields();
            $createData = [];
            if (empty($initContactFields)) {
                return;
            }

            foreach ($initContactFields as $field) {
                $createData[] = [
                    'name' => $field['name'],
                    'label' => $field['label'],
                    'type' => $field['type'],
                    'options' => Json::encode($field['options']),
                    'order' => $field['order'],
                    'status' => $field['status'],
                    'is_sys' => $field['isSys'],
                    'field_type' => $field['fieldType'],
                    'corp_id' => $corpId,
                ];
            }

            if (empty($createData)) {
                return;
            }

            $this->contactFieldService->createContactFields($createData);
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('初始化企业客户自定义字段失败，错误信息：%s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }
}
